//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#include <core.h>
#include <bsp.h>
//#include <cpu.h>
#include <timer.h>
#include <nu_api.h>
#include <Zenr_api.h>

extern void CDECL HandleTimers();
extern void Schedule();
extern "C" void CDECL NotifyDeviceCaller();
extern Int32 g_playThenAllDevicesDown;
EXTERN_C void NotifyByIsr(int eType, int nCode, void *pParam);
Bool32 g_allDevicesDown = FALSE;
Bool32 g_sleeped = FALSE;

extern uint_t UpdateSystemTime();
EXTERN void UpdateCurrentThreadTime(uint_t uTicks, bool_t bUserMode);
void UpDateTimeForIdle() {
    uint_t uLostTicks = UpdateSystemTime();

//    kprintf("System time: %d.%d\n",
//            g_systemTime.seconds, g_systemTime.microseconds);

    UpdateCurrentThreadTime(uLostTicks, FALSE);

    bool_t bOriginalPreemption = DzDisablePreemption();
    HandleTimers();
    RestorePreemptionByIsr(bOriginalPreemption);
}

EXTERN_C void CDECL BspIdle()
{
    //Notify CPU PowerManager module
	if (g_allDevicesDown && !g_playThenAllDevicesDown) {
	    //kprintf("!!!!! Elastos is going to Sleep !!!!!\n");
        //uint32_t uFlags = __SaveFlagsAndCli();
	    nu_Schedule_TimerControl(0);
	    zapi_System->allDevicesShutdown();
        g_sleeped = TRUE;
        //__RestoreIF(uFlags);
	}
    nu_Retrieve_Event(INFINITE);
    bool_t bOriginalPreemption = DzDisablePreemption();
    UpDateTimeForIdle();
    RestorePreemptionByIsr(bOriginalPreemption);
    NotifyDeviceCaller();
    Schedule();
}

EXTERN_C void CDECL BspHalt()
{
    // BUG: Not implement
    while (TRUE) {
    }
}

EXTERN_C void CDECL BspReboot()
{
    nu_bspSoftwareReset();
}
